# -*- coding: UTF8 -*-
import win32serviceutil
import win32service 
import win32event
import winerror
import servicemanager
import os, sys
#import ckcalerter
import subprocess, psutil
import pdb


#获取脚本文件的当前路径
def cur_file_dir():
    #获取脚本路径
    path = sys.path[0]
    #判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是py2exe编译后的文件，则返回的是编译后的文件路径
    #path=os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
    if os.path.isdir(path):
        return path
    elif os.path.isfile(path):
        return os.path.dirname(path)

def start_proc(path):
    return subprocess.Popen(path)

def kill_proc_tree(pid, including_parent=True):
    parent = psutil.Process(pid)
    children = parent.children(recursive=True)
    for child in children:
        child.kill()
    psutil.wait_procs(children, timeout=5)
    if including_parent:
        parent.kill()
        parent.wait(5)

def mylog(msg):
    f = file('C:\\NewsCollector\\crawler\\mylog' + str(os.getpid()) + '.txt', 'a')
    f.write(msg)
    f.write('\r\n')
    f.close()
        
class PythonService(win32serviceutil.ServiceFramework): 

    # 服务名
    _svc_name_ = "NewsCollectorService"  
    # 服务在windows系统中显示的名称
    _svc_display_name_ = "NewsCollector Service"   
    #服务的描述
    _svc_description_ = "NewsCollector Service for Windows"   

    def __init__(self, args): 
        win32serviceutil.ServiceFramework.__init__(self, args) 
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.run = True
        
    def SvcDoRun(self):
        #while self.run:
        #ckcalerter.maina()
        sp1_path = cur_file_dir() + os.sep + "alertServer" + os.sep + "ckcalerter.py"
        sp1_param = ""
        self.sp1 = subprocess.Popen(["python", sp1_path, sp1_param])

        sp2_path = cur_file_dir() + os.sep + "CollectSpider" + os.sep + "run.bat"
        self.sp2 = start_proc(sp2_path)
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
        
    def SvcStop(self): 
        # 停止服务
        self.run = False
        #ckcalerter.mainb()
	try:
            kill_proc_tree(self.sp2.pid)
        except Exception, e:
            print e
        sp2u_path = cur_file_dir() + os.sep + "CollectSpider" + os.sep + "runupdate.bat"
        self.sp2u = start_proc(sp2u_path)
            
        self.sp1.kill()
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 
        win32event.SetEvent(self.hWaitStop)
        
if __name__=='__main__':
    if len(sys.argv) == 1:
        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(PythonService)
            servicemanager.Initialize('PythonService', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error, details:
            if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(PythonService)
